/*
 * @lc app=leetcode.cn id=19 lang=cpp
 *
 * [19] 删除链表的倒数第 N 个结点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        auto slow = head, fast = head;
        while (n--) {
            if (fast == nullptr)
                return nullptr;
            
            fast = fast->next;
        }

        if (fast == nullptr) {
            auto pNext = head->next;
            delete head;
            return pNext;
        }

        for (;fast->next != nullptr; 
                slow = slow->next, fast = fast->next);
        
        auto pNext = slow->next;
        slow->next = pNext->next;
        delete pNext;

        return head;
    }
};
// @lc code=end

